package com.suning.sawp.service.impl.bi;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.suning.nsfdas.dto.BrandSale;
import com.suning.nsfdas.dto.BrandSaleDto;
import com.suning.nsfdas.dto.BrandSaleQry;
import com.suning.nsfdas.dto.CmmdtySale;
import com.suning.nsfdas.dto.CmmdtySaleAvePrice;
import com.suning.nsfdas.dto.CmmdtySaleAvePriceQry;
import com.suning.nsfdas.dto.CmmdtySaleDetail;
import com.suning.nsfdas.dto.CmmdtySaleDetailQry;
import com.suning.nsfdas.dto.CmmdtySaleListQry;
import com.suning.nsfdas.dto.Coupon;
import com.suning.nsfdas.dto.QueryParam;
import com.suning.nsfdas.dto.QueryResult;
import com.suning.nsfdas.dto.ResponseContent;
import com.suning.rsf.consumer.ServiceLocator;
import com.suning.sawp.dto.bi.BiSaleAmountDto;
import com.suning.sawp.dto.bi.CmmdtyAvgPriceDto;
import com.suning.sawp.dto.bi.CmmdtySaleDetailDto;
import com.suning.sawp.dto.bi.CmmdtySaleDetailsDto;
import com.suning.sawp.dto.bi.CouponDto;
import com.suning.sawp.dto.bi.SaleCmmdtyDto;
import com.suning.sawp.dto.bi.TopBrandDto;
import com.suning.sawp.intf.bi.BiCmmdtyService;
import com.suning.sawp.service.util.DJStringUtils;
import com.suning.sawp.service.util.DateUtils;

/**
 * 
 * 〈一句话功能简述〉单品数据<br>
 * 〈功能详细描述〉
 *
 * @author 17033093
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Service
public class BiCmmdtyServiceImpl implements BiCmmdtyService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BiCmmdtyServiceImpl.class);

    /**
     * 按销售额排序
     */
    private static final String ORDER_BY_AMOUNT = "0";

    /**
     * 1按销量排序
     */
    @SuppressWarnings("unused")
    private static final String ORDER_BY_CNT = "1";

    /**
     * 1按月查询
     */
    private static final String SEARCH_BY_MONTH = "1";

    /**
     * 2按日查询
     */
    private static final String SEARCH_BY_DAY = "2";

    /**
     * 第1个元素
     */
    private static final int FIRST_ELE = 0;

    /**
     * 日类型日期长度YYYY-MM-DD
     */
    private static final int DAY_DATE_LENGTH = 10;

    /**
     * 单品RSF接口服务
     */
    com.suning.nsfdas.service.CmmdtySaleService cmmdtySaleService = ServiceLocator.getService(
            com.suning.nsfdas.service.CmmdtySaleService.class, null);

    /**
     * 品牌RSF接口服务
     */
    com.suning.nsfdas.service.BrandSaleService brandSaleService = ServiceLocator.getService(
            com.suning.nsfdas.service.BrandSaleService.class, null);

    /**
     * 日维度查询最高销售额的单品信息
     */
    @Override
    public SaleCmmdtyDto queryTopSaleCmmdtyByDay(String storeCode, String cateCode, String day) {
        LOGGER.info("queryTopSaleCmmdtyByDay. storeCode:{}, cateCode:{}, day:{}", new Object[] { storeCode, cateCode,
                day });
        SaleCmmdtyDto dto = new SaleCmmdtyDto();
        if (StringUtils.isBlank(storeCode) || StringUtils.isBlank(day)) {
            LOGGER.error("queryTopSaleCmmdtyByDay params is null");
            return dto;
        }
        return queryTopSaleCmmdty(storeCode, cateCode, day, SEARCH_BY_DAY);
    }

    /**
     * 月维度查询最高销售额的单品信息
     */
    @Override
    public SaleCmmdtyDto queryTopSaleCmmdtyByMonth(String storeCode, String cateCode, String month) {
        LOGGER.info("queryTopSaleCmmdtyByMonth. storeCode:{}, cateCode:{}, month:{}", new Object[] { storeCode,
                cateCode, month });
        SaleCmmdtyDto dto = new SaleCmmdtyDto();
        if (StringUtils.isBlank(storeCode) || StringUtils.isBlank(month)) {
            LOGGER.error("queryTopSaleCmmdtyByMonth params is null");
            return dto;
        }
        return queryTopSaleCmmdty(storeCode, cateCode, month, SEARCH_BY_MONTH);
    }

    private SaleCmmdtyDto queryTopSaleCmmdty(String storeCode, String cateCode, String time, String searchType) {
        QueryParam<CmmdtySaleListQry> cmdQryAll = new QueryParam<CmmdtySaleListQry>();
        cmdQryAll.setPageNumber(1);
        cmdQryAll.setPageSize(10);
        CmmdtySaleListQry cmdQry = new CmmdtySaleListQry();
        cmdQry.setSortType(ORDER_BY_AMOUNT);
        cmdQry.setStoreCode(storeCode);
        // cateCode为空，查询8大品类单品
        if (StringUtils.isNotBlank(cateCode)) {
            cmdQry.setBuCode(cateCode);
        }
        cmdQry.setQueryDate(time);
        cmdQry.setQueryType(searchType);
        cmdQryAll.setRequestObject(cmdQry);

        String cmmdtyCode = "";
        String cmmdtyName = "";
        BigDecimal saleCnt = BigDecimal.ZERO;
        BigDecimal saleMoney = BigDecimal.ZERO;
        try {
            ResponseContent<CmmdtySale> rsp = cmmdtySaleService.queryCmmdtySaleList(cmdQryAll);
            LOGGER.info("queryCmmdtySaleList rsp:" + rsp);
            if (null != rsp && ResponseContent.SUCCESS.equals(rsp.getResponseCode()) && null != rsp.getQueryResult()) {
                if (CollectionUtils.isNotEmpty(rsp.getQueryResult().getResultObject())) {
                    CmmdtySale sale = rsp.getQueryResult().getResultObject().get(FIRST_ELE);
                    if (null != sale) {
                        cmmdtyCode = sale.getCmmdtyCode();
                        cmmdtyName = sale.getCmmdtyName();
                        saleCnt = sale.getSaleAmount();
                        saleMoney = sale.getSaleMoney();
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("queryTopSaleCmmdty failed.", e);
        }
        return new SaleCmmdtyDto(cmmdtyCode, cmmdtyName, DJStringUtils.bigDecimal2IntStr(saleCnt),
                BiSaleAmountDto.valueOf(saleMoney));
    }

    /**
     * 日月维度查询品类下topN品牌列表<br>
     * 
     * @param date YYYY-MM-DD、YYYY-MM
     */
    @Override
    public List<TopBrandDto> queryTopNBrandList(String storeCode, String cateCode, String date) {
        LOGGER.info("queryTopNBrandListByDate. storeCode:{},cateCode:{},date:{}", new Object[] { storeCode, cateCode,
                date });
        List<TopBrandDto> list = new ArrayList<TopBrandDto>();
        if (StringUtils.isBlank(storeCode) || StringUtils.isBlank(cateCode) || StringUtils.isBlank(date)) {
            LOGGER.error("queryTopNBrandListByDate params is null");
            return list;
        }
        BrandSaleQry cmdQry = new BrandSaleQry();
        cmdQry.setSiteCode(storeCode);
        cmdQry.setBuCode(cateCode);
        // 日YYYY-MM-DD
        if (date.length() == DAY_DATE_LENGTH) {
            cmdQry.setQueryTime(DateUtils.getDateStrByFormat(
                    DateUtils.getDateByStr(date, DateUtils.DEFAULT_DATE_PATTERN), DateUtils.YYYYMMDD_PATTERN));
            cmdQry.setQueryType(SEARCH_BY_DAY);
        } else {
            // 月 YYYY-MM
            cmdQry.setQueryTime(DateUtils.getDateStrByFormat(
                    DateUtils.getDateByStr(date, DateUtils.DEFAULT_MONTH_PATTERN), DateUtils.YYYYMM_PATTERN));
            cmdQry.setQueryType(SEARCH_BY_MONTH);
        }
        TopBrandDto topBrand;
        try {
            ResponseContent<BrandSaleDto> rsp = brandSaleService.queryCmmdtySaleBrand(cmdQry);
            LOGGER.info("queryCmmdtySaleBrand rsp:" + rsp);
            if (null != rsp && ResponseContent.SUCCESS.equals(rsp.getResponseCode()) && null != rsp.getResponseObject()) {
                List<BrandSale> brandList = rsp.getResponseObject().getCmmdtySaleBrandList();
                if (CollectionUtils.isNotEmpty(brandList)) {
                    for (BrandSale brand : brandList) {
                        if (null == brand) {
                            continue;
                        }
                        topBrand = new TopBrandDto();
                        topBrand.setBrandCode(brand.getBrandCode());
                        topBrand.setBrandName(brand.getBrandName());
                        list.add(topBrand);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("queryTopNBrandList failed.", e);
        }
        return list;
    }

    /**
     * 日月维度查询单品平均单价列表
     */
    @Override
    public CmmdtyAvgPriceDto queryCmmdtyAvgPriceList(String storeCode, String brandCode, String date, Integer pageNo,
            Integer pageSize) {
        LOGGER.info("queryCmmdtyAvgPriceList. storeCode:{},brandCode:{},date:{},pageNo:{},pageSize:{}", new Object[] {
                storeCode, brandCode, date, pageNo, pageSize });
        CmmdtyAvgPriceDto dto = new CmmdtyAvgPriceDto();
        if (StringUtils.isBlank(storeCode) || StringUtils.isBlank(brandCode) || StringUtils.isBlank(date)) {
            LOGGER.error("queryCmmdtyAvgPriceList params is null");
            return dto;
        }
        if (null == pageNo) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }

        CmmdtySaleAvePriceQry cmdQry = new CmmdtySaleAvePriceQry();
        cmdQry.setStoreCode(storeCode);
        cmdQry.setBrandCode(brandCode);
        if (date.length() == DAY_DATE_LENGTH) {
            // 日YYYY-MM-DD
            cmdQry.setQueryDate(DateUtils.getDateStrByFormat(
                    DateUtils.getDateByStr(date, DateUtils.DEFAULT_DATE_PATTERN), DateUtils.YYYYMMDD_PATTERN));
            cmdQry.setQueryType(SEARCH_BY_DAY);
        } else {
            // 月YYYY-MM
            cmdQry.setQueryDate(DateUtils.getDateStrByFormat(
                    DateUtils.getDateByStr(date, DateUtils.DEFAULT_MONTH_PATTERN), DateUtils.YYYYMM_PATTERN));
            cmdQry.setQueryType(SEARCH_BY_MONTH);
        }
        QueryParam<CmmdtySaleAvePriceQry> cmdQryAll = new QueryParam<CmmdtySaleAvePriceQry>();
        cmdQryAll.setPageSize(pageSize);
        cmdQryAll.setPageNumber(pageNo);
        cmdQryAll.setRequestObject(cmdQry);

        List<SaleCmmdtyDto> list = new ArrayList<SaleCmmdtyDto>();
        try {
            ResponseContent<CmmdtySaleAvePrice> rsp = cmmdtySaleService.queryCmmdtySaleAvePrice(cmdQryAll);
            LOGGER.info("queryCmmdtySaleAvePrice rsp:" + rsp);
            if (null != rsp && ResponseContent.SUCCESS.equals(rsp.getResponseCode()) && null != rsp.getQueryResult()) {
                QueryResult<CmmdtySaleAvePrice> result = rsp.getQueryResult();
                dto.setTotalSize(String.valueOf(result.getTotalCount()));
                if (CollectionUtils.isNotEmpty(result.getResultObject())) {
                    for (CmmdtySaleAvePrice price : result.getResultObject()) {
                        if (null == price) {
                            continue;
                        }
                        SaleCmmdtyDto cmmdtyAvgPrice = new SaleCmmdtyDto();
                        cmmdtyAvgPrice.setCmmdtyCode(price.getCmmdtyCode());
                        cmmdtyAvgPrice.setCmmdtyName(price.getCmmdtyName());
                        cmmdtyAvgPrice.setSaleAmount(BiSaleAmountDto.valueOf(price.getSaleMoney()));
                        cmmdtyAvgPrice.setSaleCnt(DJStringUtils.bigDecimal2IntStr(price.getSaleAmount()));
                        cmmdtyAvgPrice.setAvgPrice(BiSaleAmountDto.valueOfLow(price.getAveragePrice()));
                        list.add(cmmdtyAvgPrice);
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("queryCmmdtyAvgPriceList failed.", e);
        }
        dto.setCmmdtyAvgPriceList(list);

        return dto;
    }

    /**
     * 查询单品信息列表
     */
    @Override
    public CmmdtySaleDetailsDto queryCmmdtySaleList(String storeCode, String cateCode, String brandCode,
            String cmmdtyCode, String sortType, String date, Integer pageNo, Integer pageSize) {
        LOGGER.info(
                "queryCmmdtySaleList.storeCode:{},cateCode:{},brandCode:{},cmmdtyCode:{},sortType:{},date:{},pageNo:{},pageSize:{}",
                new Object[] { storeCode, cateCode, brandCode, cmmdtyCode, sortType, date, pageNo, pageSize });
        CmmdtySaleDetailsDto dto = new CmmdtySaleDetailsDto();
        if (StringUtils.isBlank(storeCode) || StringUtils.isBlank(date)) {
            LOGGER.error("queryCmmdtySaleList param is null");
            return dto;
        }
        if (null == pageNo) {
            pageNo = 1;
        }
        if (null == pageSize) {
            pageSize = 10;
        }

        CmmdtySaleListQry cmdQry = new CmmdtySaleListQry();
        cmdQry.setStoreCode(storeCode);
        cmdQry.setBuCode(cateCode);
        cmdQry.setBrandCode(brandCode);
        cmdQry.setCmmdtyCode(cmmdtyCode);
        cmdQry.setSortType(sortType);
        if (date.length() == DAY_DATE_LENGTH) {
            // 日YYYY-MM-DD
            cmdQry.setQueryDate(DateUtils.getDateStrByFormat(
                    DateUtils.getDateByStr(date, DateUtils.DEFAULT_DATE_PATTERN), DateUtils.YYYYMMDD_PATTERN));
            cmdQry.setQueryType(SEARCH_BY_DAY);
        } else {
            // 月YYYY-MM
            cmdQry.setQueryDate(DateUtils.getDateStrByFormat(
                    DateUtils.getDateByStr(date, DateUtils.DEFAULT_MONTH_PATTERN), DateUtils.YYYYMM_PATTERN));
            cmdQry.setQueryType(SEARCH_BY_MONTH);
        }
        QueryParam<CmmdtySaleListQry> cmdQryAll = new QueryParam<CmmdtySaleListQry>();
        cmdQryAll.setPageSize(pageSize);
        cmdQryAll.setPageNumber(pageNo);
        cmdQryAll.setRequestObject(cmdQry);
        List<SaleCmmdtyDto> list = new ArrayList<SaleCmmdtyDto>();
        try {
            ResponseContent<CmmdtySale> rsp = cmmdtySaleService.queryCmmdtySaleList(cmdQryAll);
            LOGGER.info("queryCmmdtySaleList rsp:" + rsp);
            if (null != rsp && ResponseContent.SUCCESS.equals(rsp.getResponseCode()) && null != rsp.getQueryResult()) {
                QueryResult<CmmdtySale> result = rsp.getQueryResult();
                dto.setTotalSize(String.valueOf(result.getTotalCount()));
                if (CollectionUtils.isNotEmpty(result.getResultObject())) {
                    for (CmmdtySale sale : result.getResultObject()) {
                        if (null == sale) {
                            continue;
                        }
                        list.add(new SaleCmmdtyDto(sale.getCmmdtyCode(), sale.getCmmdtyName(), DJStringUtils
                                .bigDecimal2IntStr(sale.getSaleAmount()), BiSaleAmountDto.valueOf(sale.getSaleMoney(),
                                BiSaleAmountDto.UNIT_WAN)));
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("queryCmmdtySaleList failed", e);
        }
        dto.setCmmdyList(list);
        return dto;
    }

    /**
     * 查询单品详情
     */
    @Override
    public CmmdtySaleDetailDto queryCmmdtySaleDetail(String storeCode, String cmmdtyCode, String date) {
        LOGGER.info("queryCmmdtySaleDetail.storeCode:{},cmmdtyCode:{},date:{}", new Object[] { storeCode, cmmdtyCode,
                date });
        CmmdtySaleDetailDto dto = new CmmdtySaleDetailDto();
        if (StringUtils.isBlank(storeCode) || StringUtils.isBlank(cmmdtyCode) || StringUtils.isBlank(date)) {
            LOGGER.error("queryCmmdtySaleDetail param is null");
            return dto;
        }

        CmmdtySaleDetailQry cmdQry = new CmmdtySaleDetailQry();
        cmdQry.setSiteCode(storeCode);
        cmdQry.setCmmdtyCode(cmmdtyCode);
        // 日YYYY-MM-DD
        if (date.length() == DAY_DATE_LENGTH) {
            cmdQry.setQueryTime(DateUtils.getDateStrByFormat(
                    DateUtils.getDateByStr(date, DateUtils.DEFAULT_DATE_PATTERN), DateUtils.YYYYMMDD_PATTERN));
            cmdQry.setQueryType(SEARCH_BY_DAY);
        } else {
            // 月YYYY-MM
            cmdQry.setQueryTime(DateUtils.getDateStrByFormat(
                    DateUtils.getDateByStr(date, DateUtils.DEFAULT_MONTH_PATTERN), DateUtils.YYYYMM_PATTERN));
            cmdQry.setQueryType(SEARCH_BY_MONTH);
        }
        try {
            ResponseContent<CmmdtySaleDetail> rsp = cmmdtySaleService.queryCmmdtySaleDetail(cmdQry);
            LOGGER.info("queryCmmdtySaleDetail rsp:" + rsp);
            if (null != rsp && ResponseContent.SUCCESS.equals(rsp.getResponseCode())) {
                CmmdtySaleDetail detail = rsp.getResponseObject();
                if (null != detail) {
                    dto.setCmmdtyCode(detail.getCmmdtyCode());
                    dto.setCmmdtyName(detail.getCmmdtyName());
                    dto.setAvgPrice(BiSaleAmountDto.valueOfLow(DJStringUtils.bigDecimal(detail.getAvePrice())));
                    dto.setRefundAmt(BiSaleAmountDto.valueOf(detail.getRefundAmt()));
                    dto.setSaleAmt(BiSaleAmountDto.valueOf(detail.getSaleAmt()));
                    String refundNum = "0";
                    if (StringUtils.isNotBlank(detail.getRefundNum())) {
                        refundNum = String.valueOf(DJStringUtils.bigDecimal(detail.getRefundNum()).intValue());
                    }
                    dto.setRefundNum(refundNum);
                    String saleNum = "0";
                    if (StringUtils.isNotBlank(detail.getSaleNum())) {
                        saleNum = String.valueOf(DJStringUtils.bigDecimal(detail.getSaleNum()).intValue());
                    }
                    dto.setSaleNum(saleNum);
                    dto.setSalePayTotal(BiSaleAmountDto.valueOf(detail.getSalePayTotal()));
                    String saleNumTotal = "0";
                    if (StringUtils.isNotBlank(detail.getSaleNumTotal())) {
                        saleNumTotal = String.valueOf(DJStringUtils.bigDecimal(detail.getSaleNumTotal()).intValue());
                    }
                    dto.setSaleNumTotal(saleNumTotal);
                    dto.setSalesPersent(DJStringUtils.getOneScale(detail.getSalesPersent()));
                    
                    dto.setDiscountList(transferCoupon(detail.getDiscountList()));
                    dto.setDiscountTotal(BiSaleAmountDto.valueOf(DJStringUtils.bigDecimal(detail.getDiscountTotal()),
                            BiSaleAmountDto.UNIT_NORMAL));
                    dto.setPreperentialList(transferCoupon(detail.getPreperentialList()));
                    dto.setPreperentialTotal(BiSaleAmountDto.valueOf(
                            DJStringUtils.bigDecimal(detail.getPreperentialTotal()), BiSaleAmountDto.UNIT_NORMAL));
                    dto.setOtherTotal(BiSaleAmountDto.valueOf(DJStringUtils.bigDecimal(detail.getOtherTotal()),
                            BiSaleAmountDto.UNIT_NORMAL));
                    dto.setTotalDiscountAmt(BiSaleAmountDto.valueOf(DJStringUtils.bigDecimal(detail.getTotalDiscountAmt()),
                            BiSaleAmountDto.UNIT_NORMAL));
                    return dto;
                }
            }
        } catch (Exception e) {
            LOGGER.error("queryCmmdtySaleDetail failed.", e);
        }

        return dto;
    }

    private List<CouponDto> transferCoupon(List<Coupon> list) {
        List<CouponDto> dtoList = new ArrayList<CouponDto>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (Coupon coupon : list) {
                if (null == coupon) {
                    continue;
                }
                CouponDto dto = new CouponDto();
                dto.setKey(coupon.getKey());
                dto.setName(coupon.getName());
                dto.setValue(BiSaleAmountDto.valueOf(DJStringUtils.bigDecimal(coupon.getValue()),
                        BiSaleAmountDto.UNIT_NORMAL));
                dtoList.add(dto);
            }
        }
        return dtoList;
    }

}
